package com.gdth.bank.model;

import java.io.File;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import android.os.Environment;
import android.os.Handler;
import android.widget.ImageView;

import com.gdth.bank.BankApplication;
import com.gdth.bank.bean.DownloadBean;
import com.gdth.http.body.ProgressRequestBody;
import com.gdth.http.callback.DownLoadCallback;
import com.gdth.http.callback.UploadCallback;
import com.gdth.http.listener.ProgressListener;
import com.gdth.http.listener.impl.ProgressListenerImpl;
import com.gdth.http.listener.impl.UIProgressListenerImpl;
import com.gdth.http.method.EngDNS;
import com.gdth.http.method.ProgressHelper;
import com.gdth.http.method.httpsUtils;
import com.gdth.utils.GsonUtil;

public class DownloadModel {
	private OkHttpClient client;
	
	/**
     * 单例模式
     * @author arvin
     *
     */
	private static class SingletonHolder{
		private static final DownloadModel instance = new DownloadModel();
	}
	
	public static final DownloadModel getInstance(){
		return SingletonHolder.instance;
	}
	
	private String download;
	private String upload;
	
	private DownloadModel(){
		client = new OkHttpClient.Builder()
								    //设置超时，不设置可能会报异常
								    .connectTimeout(1000, TimeUnit.MINUTES)
								    .readTimeout(1000, TimeUnit.MINUTES)
								    .writeTimeout(1000, TimeUnit.MINUTES)
									.dns(new EngDNS())
								    .sslSocketFactory(httpsUtils.getSSLSocketFactory())
						    		.hostnameVerifier(httpsUtils.getHostnameVerifier())
								    .build();
		
		upload = BankApplication.mInstance.url + "bank/upload!fileUploadByPublic.do";
		download = BankApplication.mInstance.url + "bank/fileDownLoadOperate!downLoadByName.do";
	}
	
	
	public void upload(DownloadBean bean){
		String filePath = bean.getLocalPath();
		if(!filePath.startsWith(Environment.getExternalStorageDirectory().toString())){
			filePath = Environment.getExternalStorageDirectory() + filePath;
		}
		File file = new File(filePath);
		
		upload(file, bean, null);
	}
	public void uploadFJ(DownloadBean bean, Handler mHandler){
		String filePath = bean.getLocalPath();
		if(!filePath.startsWith(Environment.getExternalStorageDirectory().toString())){
			filePath = Environment.getExternalStorageDirectory() + filePath;
		}
		File file = new File(filePath);
		
		upload(file, bean, mHandler);
	}
	
	public void upload(DownloadBean bean, Handler mHandler){
		File file = new File(Environment.getExternalStorageDirectory() + bean.getLocalPath());
		
		upload(file, bean, mHandler);
	}
	
	public void upload(File file, DownloadBean bean, Handler mHandler){
		//这个是非ui线程回调，不可直接操作UI
        final ProgressListenerImpl progressListener = new ProgressListenerImpl();

        //构造上传请求，类似web表单
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("upload", file.getName(), RequestBody.create(null, file))
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"upload\";filename=\"1.png\""), 
                		RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .build();

        String content = GsonUtil.getGson().toJson(bean);
//        String content =bean.toString();
        String url = upload + "?content=" + content;
        
        final Request request = new Request.Builder().url(url).build();
        ProgressHelper.addProgressResponseListener(client, requestBody, progressListener).newCall(request).enqueue(new UploadCallback(mHandler, 1));
	}
	
	/**
	 * 下载文件
	 * @param name
	 */
	public void download(DownloadBean bean, ImageView mImageView) {
		download(bean, mImageView, null);
    }
	
	public void download(DownloadBean bean, ImageView mImageView, Handler handler) {
		String content = GsonUtil.getGson().toJson(bean);
        
		String url = download + "?content=" + content;
		
        final ProgressListener progressResponseListener = new ProgressListenerImpl();

        //构造请求
        final Request request = new Request.Builder().url(url).build();
        ProgressHelper.addProgressResponseListener(client, progressResponseListener).newCall(request).enqueue(new DownLoadCallback(mImageView, handler));
	}
	
	/**
	 * 获取请求体
	 * @param path
	 * @param name
	 * @return
	 */
	@SuppressWarnings("unused")
	private ProgressRequestBody getProgressRequestBody(String path, String name){
		RequestBody requestBody = getRequestBody(path, name);
		ProgressRequestBody body = ProgressHelper.addProgressRequestListener(requestBody, new UIProgressListenerImpl());
	
		return body;
	}
	
	/**
	 * 利用MultipartBody构造请求头
	 * @return
	 */
	private RequestBody getRequestBody(String path, String name){
		File file = new File(path);
		RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("name", name)
                .addFormDataPart("upload", file.getName(), RequestBody.create(null, file))
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"upload\";filename=\""+name+"\""), RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .build();
		
		return requestBody;
	}
	
}
